package com.demo.react.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class AuthorInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 得到请求地址 此地址不包含参数
		String requestUrl = request.getRequestURL().toString();
		System.out.println(requestUrl);
		String[] split = requestUrl.split("localhost:8080/");
		System.out.println(split[1]);
		if (split[1].equals("react/login")) {
			System.err.println(" AuthorInterceptor  preHandle  --登陆请求");
			return true;
		} else {
			System.out.println(" AuthorInterceptor  preHandle  --其他请求！");
			String tokenValue = request.getParameter("token");
			// System.err.println("Token ---" + tokenValue);
			System.err.println("Token ---" + tokenValue);
			if ("null".equals(tokenValue) || null == tokenValue || tokenValue.length() == 0) {
				// set
				request.setCharacterEncoding("UTF-8");
				response.setCharacterEncoding("UTF-8");
				response.setHeader("Access-Control-Allow-Origin", "*");
				response.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
				response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
				response.setHeader("Content-Type", "application/json;charset=utf-8");
				// add
//				response.addHeader("result", "身份验证失败,请重新登录");
//				response.setStatus(401);

//				PrintWriter out = response.getWriter();
//				String msg = "身份验证失败,请重新登录!";
//				out.write(msg);
//				return false;
				return true;
			}
			return true;
		}

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
